package com.codepilot.server.service.impl;

import com.codepilot.server.mapper.RecordMapper;
import com.codepilot.server.model.entity.Record;
import com.codepilot.server.service.RecordService;
import com.codepilot.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private UserService userService;

    public List<Record> getRecordList(Integer userId) {
        return recordMapper.getRecordList(userId);
    }
    public Integer createRecord(Integer userId, Integer problemUid) {
        // 查找数据库内该题是否有未完成的记录
        Record latest = recordMapper.getNotDoneRecord(userId, problemUid);
        // 若有则直接修改该记录，更新开始时间
        if (latest != null) {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            latest.setStartTime(formatter.format(date));
            return recordMapper.updateRecord(latest);
        }
        // 若没有则新建记录
        return recordMapper.insertRecord(userId, problemUid);
    }
    public Integer renewRecord(Record record) {
        return recordMapper.updateRecord(record);
    }
    public Integer finishRecord(Record record) {
        // 判断新记录的做题状态
        // 查找有没有待完成的记录
        Record target = recordMapper.getNotDoneRecord(record.getUserId(), record.getProblemUid());
        if (target != null) {
            // 更新记录状态为已完成
            record.setId(target.getId());
            return recordMapper.updateRecord(record);
        }
        else
            return 0;
    }
}
